<template>
  <el-dialog
    v-model="state.show"
    title="费用信息"
    width="800px"
    modal-class="docFee-information-dailog"
  >
    <el-form
      v-if="showBtn"
      ref="addFormRef"
      :model="state.addForm"
      label-suffix=":"
      label-width="90px"
      :rules="state.rules"
      :show-message="false"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="收付类型">
            <el-select
              v-model="state.addForm.receivedOrPaid"
              placeholder="请选择"
              clearable
              filterable
              disabled
            >
              <el-option label="应收" value="应收"> </el-option>
              <el-option label="应付" value="应收"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结算单位">
            <el-select
              v-model="state.addForm.customerType"
              filterable
              remote
              reserve-keyword
              placeholder="请选择"
              size="small"
              :remote-method="selectEntOptions"
              :loading="state.customerloading"
              style="width: 100%"
            >
              <el-option
                v-for="item in state.customerList"
                :key="item.id"
                :label="item.label"
                :value="item.value"
                @click="getEntOption(item)"
                ><span style="float: left">{{ item.leftName }}</span>
                <span style="float: right">{{ item.rigthName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="费用名称">
            <el-select
              v-model="state.addForm.feeName"
              filterable
              remote
              reserve-keyword
              placeholder="请选择"
              size="small"
              :remote-method="selectFeeOptions"
              :loading="state.feeloading"
              style="width: 100%"
            >
              <el-option
                v-for="item in state.feeList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
                @click="getFeeLeverOption(item)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="币种">
            <el-select
              v-model="state.addForm.currency"
              filterable
              remote
              placeholder="请选择"
              size="small"
              :remote-method="queryCurrency"
              remote-show-suffix
              :loading="state.currencyLoading"
              style="width: 100%"
            >
              <el-option
                v-for="item in state.currencyList"
                :key="item.label"
                :label="item.label"
                @click="getCurOption(item)"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位">
            <el-select
              v-model="state.addForm.unit"
              filterable
              remote
              placeholder="请选择"
              size="small"
              :remote-method="queryUnit"
              remote-show-suffix
              :loading="state.unitLoading"
              style="width: 100%"
            >
              <el-option
                v-for="item in state.unitList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="input-number-style">
          <el-form-item label="数量">
            <el-input-number
              v-model="state.addForm.feeCount"
              placeholder="请输入"
              :precision="0"
              :min="1"
              :controls="false"
              @change="calulateValue"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" class="input-number-style">
          <el-form-item label="单价" prop="pkgs">
            <el-input-number
              v-model="state.addForm.price"
              placeholder="请输入"
              :precision="2"
              @change="calulateValue"
              :controls="false"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实际金额">
            <el-input
              v-model="state.addForm.feeAmount"
              placeholder="请输入"
              disabled
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="发票类型">
            <el-select
              v-model="state.addForm.invoiceType"
              filterable
              remote
              placeholder="请选择"
              size="small"
              :remote-method="queryInoviveType"
              remote-show-suffix
              :loading="state.inoviveLoading"
              style="width: 100%"
            >
              <el-option
                v-for="item in state.inovive"
                :key="item.label"
                :label="item.label"
                :value="item.value"
                @click="getInvoiceOption(item)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票金额">
            <el-input
              v-model="state.addForm.invoiceAmount"
              placeholder="请输入"
              disabled
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="container-table" v-if="!showBtn">
      <div class="item item-layout">
        <div class="label-item">收付类型</div>
        <div class="content-item">
          {{ state.addForm.receivedOrPaid }}
        </div>
      </div>
      <div class="item item-layout">
        <div class="label-item">结算单位</div>
        <div class="content-item">
          {{ state.addForm.customerType }}
        </div>
      </div>
      <div class="item item-layout">
        <div class="label-item">费用名称</div>
        <div class="content-item">{{ state.addForm.feeName }}</div>
      </div>
      <div class="item item-layout">
        <div class="label-item">币种</div>
        <div class="content-item">{{ state.addForm.currency }}</div>
      </div>
      <div class="item item-layout">
        <div class="label-item">单位</div>
        <div class="content-item">{{ state.addForm.unit }}</div>
      </div>
      <div class="item item-layout">
        <div class="label-item">数量</div>
        <div class="content-item">{{ state.addForm.feeCount }}</div>
      </div>
      <div class="item item-layout">
        <div class="label-item">单价</div>
        <div class="content-item">{{ state.addForm.price }}</div>
      </div>
      <div class="item item-layout">
        <div class="label-item">实际金额</div>
        <div class="content-item">{{ state.addForm.feeAmount }}</div>
      </div>
      <div class="item item-layout">
        <div class="label-item">发票类型</div>
        <div class="content-item">{{ state.addForm.invoiceType }}</div>
      </div>
      <div class="item item-layout">
        <div class="label-item">发票金额</div>
        <div class="content-item">{{ state.addForm.invoiceAmount }}</div>
      </div>
    </div>
    <template #footer v-if="showBtn">
      <div>
        <el-button type="default" @click="state.show = false">取消</el-button>
        <el-button type="primary" @click="modifySubmit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineComponent, nextTick, reactive, ref } from 'vue'
import AppSearchForm from '@/components/AppSearchForm.vue'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useStore, Store } from 'vuex'
import request from '@/public/request'
import selectDown from '../newBusiness/selectDownNew.vue'
import vueBus from '@/utils/vueBus'
import { validateOnlyNumberTwo, validateNumber } from '@/utils/validate.js'

const props = defineProps({
  //控制编辑和查看
  showBtn: {
    type: Boolean,
    default: false
  },
  //控制编辑和查看
  isIncome: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['save'])

const Router = useRouter()
const Route = useRoute()
const store = useStore()

const state = reactive({
  show: false,
  addForm: {
    id: 0,
    receivedOrPaid: props.isIncome ? '应收' : '应付', //类型
    customerType: '', //往来户
    customerCode: '',
    feeName: '', //费用名称
    feeLevel: '',
    currency: '', //币种
    price: 0, //单价
    unit: '', //单位
    feeCount: 1, //数量
    feeAmount: '', //实际金额
    exchangeRate: 1, //转化汇率
    invoiceType: '', //发票类型
    feeAmountRmb: '', //折本币金额
    invoiceAmount: '',
    taxRate: 0, //税率
    taxAmount: 0, //税金
    amountIsTax: 0 //
  },
  // 获取币种
  currencyLoading: false,
  currencyList: [],
  // 结算对象
  customerloading: false,
  customerList: [],
  // 费用名称
  feeloading: false,
  feeList: [],
  // 费用名称
  inoviveLoading: false,
  inovive: [],
  // 单位
  unitLoading: false,
  unitList: [],
  // 修改还是保存
  isSave: false
})
const addFormRef = ref('')

// 新增
function modifySubmit() {
  state.show = false
  emits('save', state.addForm, state.isSave)
}

// function summary() {
//   console.log(state.addForm.price, state.addForm.feeCount, 'ccccccc')
//   state.addForm.feeAmount = state.addForm.price * state.addForm.feeCount
// }

/**
 * 查询结算对象编码数据
 * @param {string} query - 输入内容查询
 */
async function selectEntOptions(query) {
  state.customerloading = true
  request
    .get('/api/crcontactcompany/query', {
      code: query,
      PageIndex: 1,
      PageSize: 50,
      businessCategory: ''
    })
    .then((res) => {
      state.customerList = res.content.map((item) => {
        return {
          id: item.id,
          value: item.comNameCn,
          label: item.comNameCn,
          selectLabel: `${item.comCode}|${item.comNameCn}`,
          name: item.comNameCn,
          leftName: item.comCode,
          rigthName: item.comNameCn
        }
      })
    })
    .finally(() => (state.customerloading = false))
}

/**
 * 查询费用名称编码数据
 * @param {string} query - 输入内容查询
 */
async function selectFeeOptions(query) {
  state.feeloading = true
  request
    .get('/api/csfeesname/querypage', {
      KeyWords: query,
      PageIndex: 1,
      PageSize: 50
    })
    .then((res) => {
      res.content.forEach((item) => {
        item.value = item.nameCh
        item.label = item.nameCh
      })
      state.feeList = res.content
    })
    .finally(() => (state.feeloading = false))
}

// 查询获取币种
const queryUnit = async (query) => {
  state.unitLoading = true
  let res = await request.get('/api/cscontainer/querypage', {
    ContainerCode: query,
    PageIndex: 1,
    PageSize: 50
  })
  state.unitList = res.content.map((item) => {
    return {
      label: item.containerCode,
      value: item.containerCode
    }
  })
  state.unitList.push({
    label: '票',
    value: '票'
  })
  state.unitLoading = false
}

// 查询获取币种
const queryCurrency = async (query) => {
  state.currencyLoading = true
  let res = await request.get('/api/cscurrency/querypage', {
    KeyWords: query,
    PageIndex: 1,
    PageSize: 50
  })
  state.currencyList = res.content.map((item) => {
    return {
      label: item.currencyCode,
      value: item.currencyCode
    }
  })
  state.currencyLoading = false
}

// 查询获取发票类型
const queryInoviveType = async (query) => {
  state.inoviveLoading = true
  let res = await request.get('/api/csinvoicetype/querypage', {
    KeyWords: query,
    PageIndex: 1,
    PageSize: 50
  })
  res.content.forEach((item) => {
    // return {
    item.label = item.typeName
    item.value = item.typeName
    // }
  })
  state.inovive = res.content
  state.inoviveLoading = false
}

/**
 * 结算对象编码的option
 * @param {object} item - 选择的option
 */
function getEntOption(item) {
  state.addForm.customerCode = item.leftName
}
/**
 * 费用名称的option
 * @param {object} item - 选择的option
 */
function getFeeLeverOption(item) {
  state.addForm.feeLevel = item.defaultLevel
}

/**
 * 发票类型的option
 * @param {object} item - 选择的option
 */
function getInvoiceOption(item) {
  state.addForm.taxRate = item.taxRate ? item.taxRate : 0
  calulateValue()
}

/**
 * 费用名称的option
 * @param {object} item - 选择的option
 */
async function getCurOption(item) {
  let res = await request.get('/api/cscurrencyrate/queryby', {
    currencyCode: item.currencyCode
  })
  if (res.data) {
    state.addForm.exchangeRate = res.data.exchangeRate
  } else {
    state.addForm.exchangeRate = 1
  }
  calulateValue()
}

// 重新根据单价汇率和数量重新计算个值
function calulateValue(row) {
  state.addForm.feeAmount =
    (state.addForm.feeCount ? parseFloat(state.addForm.feeCount) : 1) *
    (state.addForm.price ? parseFloat(state.addForm.price) : 0)

  state.addForm.feeAmountRmb =
    (state.addForm.feeAmount ? parseFloat(state.addForm.feeAmount) : 0) *
    parseFloat(state.addForm.exchangeRate ? state.addForm.exchangeRate : 1)
  state.addForm.taxAmount =
    Math.round(
      state.addForm.feeAmountRmb *
        ((state.addForm.taxRate ? parseFloat(state.addForm.taxRate) : 0) /
          100) *
        100
    ) / 100

  state.addForm.amountIsTax =
    Math.round(
      state.addForm.feeAmountRmb *
        (1 +
          (state.addForm.taxRate ? parseFloat(state.addForm.taxRate) : 0) /
            100) *
        100
    ) / 100
}

// row：只有编辑时才会带入对应的数据
function open(row) {
  if (!row) {
    state.isSave = true
    state.addForm = {
      id: 0,
      receivedOrPaid: props.isIncome ? '应收' : '应付', //类型
      customerType: '', //往来户
      customerCode: '',
      feeName: '', //费用名称
      feeLevel: '',
      currency: '', //币种
      price: 0, //单价
      unit: '', //单位
      feeCount: 1, //数量
      feeAmount: '', //实际金额
      exchangeRate: 1, //转化汇率
      invoiceType: '', //发票类型
      invoiceAmount: '',
      feeAmountRmb: '' //折本币金额
    }
  } else {
    state.isSave = false
    state.addForm = row
    console.log(state.addForm, 'state.addForm')
  }
  state.show = true
}
defineExpose({
  open
})
</script>

<style lang="scss">
.docFee-information-dailog {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
    padding: 7px 16px 7px 16px;
  }

  .el-dialog {
    padding: 0px;
  }

  .el-dialog__body {
    padding-right: 36px;
  }

  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;
    text-align: center;
  }
}
</style>
<style lang="scss" scoped>
@import '@/styles/business/business.scss';
.from-container {
  border: 1px solid #e8e8e8;
  padding: 6px;
  margin-bottom: 8px;
}

.flex-container {
  display: flex;
  justify-content: flex-start;

  .add-use-box-info-new {
    color: #6ba5f6;
    cursor: pointer;
    width: 50px;
    height: 24px;
    display: flex;
    align-items: center;
    margin-left: 4px;
    flex: 0 0 50px;
    .addFont {
      margin-left: 3px;
      line-height: 24px;
    }
  }
}

.item {
  width: 50%;
}

.delete-icon {
  position: absolute;
  top: -5px;
  right: -4px;
  z-index: 100;
  color: #c5c5c5;
  cursor: pointer;
}

.table-header::before {
  content: '*';
  color: #f56c6c;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
  letter-spacing: 0px;
  position: absolute;
  left: 11px;
}

.input-number-style {
  :deep(.el-input-number.is-without-controls .el-input__wrapper) {
    padding: 2px 8px;
  }
  :deep(.el-input-number .el-input__inner) {
    text-align: left;
  }
}

:deep(.el-radio) {
  margin-right: 12px;
}

:deep(.el-checkbox.el-checkbox--small) {
  margin-right: 12px;
}

:deep(.el-form-item--small .el-form-item__label) {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.85);
}

:deep(.el-form--inline .el-form-item) {
  display: flex;
  margin-right: 0;
}
:deep(.el-form-item.is-error .el-checkbox__input .el-checkbox__inner) {
  border-color: #f56c6c;
}

:deep(.el-form-item--small.el-form-item) {
  margin-bottom: 10px;
}
:deep(.el-input-number--small) {
  width: 100%;
}

:deep(.el-form--inline .el-form-item) {
  display: flex;
}
</style>
